from flask import request, g

from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.libs.token_auth import login_required
from app.models.space import SpaceModel
from app.validates.space import SpaceForm, DeleteSpaceForm, SearchSpaceForm

api = Redprint('space')


@api.route('', methods=['GET'])
@login_required
def get_space():
    spaces = SpaceModel().get_all_space()
    return Success(data=spaces)


@api.route('/my', methods=['GET'])
@login_required
def get_my_space():
    # 从全局参数g中获取id
    spaces = SpaceModel().get_all_space(g.user)
    return Success(data=spaces)


@api.route('/all', methods=['GET'])
@login_required
def get_all_space():
    # 从全局参数g中获取id
    spaces = SpaceModel.get_all_space_all()
    return Success(data=spaces)


@api.route('', methods=['POST'])
@login_required
def add_space():
    form = SpaceForm().validate_and_api()
    SpaceModel.add_space(form.name.data, g.user)
    return Success()


@api.route('/<int:space_id>', methods=['DELETE'])
@login_required
def delete_space(space_id):
    SpaceModel.delete_space(space_id)
    return Success()


@api.route('/search', methods=['GET'])
@login_required
def search_space():
    form = SearchSpaceForm().validate_and_api()
    data = SpaceModel().search_space(form.keyword.data)
    return Success(data=data)
